//============================================================================
// Name        : FileReader.cpp
// Author      : Anthea Neums, Jonas Halbach
//			   :
// Description : This Class is used to read the content of a file and parse it
//					into a char string.
//============================================================================

using namespace std;
#include "FileReader.h"

FileReader::FileReader(char *filename) {
	content = NULL;
	 fileName = filename;
	 try
	 {
	 fileStream = new ifstream(fileName, ios_base::in);

	 size = calculateSize();
	 if(size > 0)
	 {
		 convertStreamToChar();
		 size = strlen(content);
	 }
	 }
	 catch(exception e)
	 {
	 }

}

char *FileReader::getContent()
{
	return content;
}

void FileReader::convertStreamToChar(){

	 ifstream file(fileName, ios_base::in);

	 if (!file.good()) {
		cout<< "Can not open file " << endl;
	 }else {

		 //save content in char array
		 content = new char[size + 1];

		 int currentPos = 0;
		 file.seekg(0, ios::beg);


		 //filter backslash
		 while (!file.eof()) {
			 char currentChar = file.get();

			 //don't take \n s a part of the pattern
			 if (currentChar!='\n' && isalpha(currentChar) && file.good()){
				 content[currentPos] = currentChar;
				 currentPos++;
			 }

		 }
		 content[currentPos]='\0';
		 file.close();
	 }
	 
}

FileReader::~FileReader() {
	fileStream->close();
	delete content;
}

int FileReader::getSize(void){
	return size;
}

/**
 * returns the number of letters in the file
 */
int FileReader::calculateSize(void) {
	size = 0;
	if (!fileStream->good()) {
		cout << "Can not open file!" << endl;
	} else {
		fileStream->seekg(0, ios::beg);
		const streampos start = fileStream->tellg();
		fileStream->seekg(0, ios::end);
		const streampos end = fileStream->tellg();
		size = end - start;
		fileStream->seekg(0, ios::beg);
	}
	return size;
}

char* FileReader::getNext (int pos, int length){
	char *retVal = new char[length + 1];
	if(pos + length <= size)
	{
		strncpy(retVal, content + pos, length);
	}
	retVal[length]= '\0';

	return retVal;
}

